// xc_lshop/pro/cart/cart.js
const app = getApp()
var actcart = require('../../../xc/sys/icart')
Page({
  mixins: [require('../../../xc/mixins/basicMixin')],
  /**
   * 页面的初始数据
   */
  data: {
    limitmodel: null,
    haslimit: -1, //是否有限时
    sumclass: 0, //已选数量
    timeData: {},
    sumprice: 0.00,
    cartlist: null,
    ischeckedall: false,
    isdelmodel: false,
    exinfo: {} // {limitconditions: {12: {maxbuy: "-100", prolimit: {107: "1"}},ubuy: {buyed: null, buying: null}}

  },
  xcloaddata: function (options, config) {
    console.log(config)
    if(config.order){
      this.setData({
        orderconfig: config.order
      })
    }
    if (config.prothem && config.prothem.themcolor) {
      var themconfig = config.prothem.themcolor.config;
      this.setData({
        themconfig: themconfig
      })
    }
    var strwhere = {}
    strwhere["status"] = 1
    var app = getApp();
    var that = this;
    app.xc_sys_config.authop.oppower("login").then(function (res) {
      if (res.status == 1) {
        that.loadcartdata()
      }
    })
  },

  changecartselect(ev) {
    var dataset = ev.currentTarget.dataset
    var idx = dataset.idx
    var item = dataset.item
    actcart.setchk(item.keyval, !item.ischecked)
    var updatemodel = {}
    updatemodel['cartlist[' + idx + '].ischecked'] = !item.ischecked
    this.setData(updatemodel)
    this.price()
    this.vildchosedall()
  },
  numchange(ev) {
    var num = parseInt(ev.detail)  
    var dataset = ev.currentTarget.dataset
    var idx = dataset.idx
    var item = dataset.item
    if (num <= 0) {
      num = 0;
  
    }
    actcart.setnum(item.keyval, num)


    //更新限购
    var cartlist = this.data.cartlist
    cartlist[idx]["num"] = num;
    var cartlist = this.setlimitnum(cartlist);
    if(num==0){
      actcart.setnum(cartlist[idx].keyval, 0)
      cartlist.splice(idx,1);
    }
    // this.setData(cartlist)

    var updatemodel = {};
    updatemodel["cartlist"] = cartlist;
    //更新限购 结束
    // var updatemodel={}
    // updatemodel['cartlist['+idx+'].num'] = num
    this.setData(updatemodel)
    this.price()


  },
  loadcartdata() {
    var that = this

    actcart.loadcartPromise().then(function (ret) {
     

        if (ret.code == "success") {
          var updatemdoel = {};
          updatemdoel["cartlist"] = ret.data;          
          that.data.exinfo = ret["exinfo"]
          updatemdoel["cartlist"] = that.setlimitnum(updatemdoel["cartlist"])
         
          that.setData(updatemdoel)
          that.price()
          that.vildchosedall()
        }

      },
      function (e) {
        console.log(e);
      }
    )
  },

  setlimitnum(cartlist) {

    var exinfo = this.data.exinfo;
  
    if (typeof (exinfo) != 'undefined') {
      var limitcompile = null
      if (exinfo["limitcompile"]) {

        limitcompile = exinfo["limitcompile"];
      } else {

        return cartlist;
      }

      var limitmodel = JSON.parse(JSON.stringify(limitcompile));

      var maxbuy = -1;
      var maxbuypro = -1;
      var limitnum = -1
      if (cartlist) {
        var temitem = null
        for (var a in cartlist) {
          temitem = cartlist[a]
          if (temitem["activityid"]) {
            var activityid = temitem["activityid"];
            var proid = temitem["proid"];  
            var actlimitmodel = limitmodel[activityid];  
            if (actlimitmodel) {
              var actprolimit = actlimitmodel["prolimit"]
              var maxbuy = parseInt(actlimitmodel["maxbuy"])
              var maxbuypro = parseInt(actlimitmodel["prolimit"][proid])
              var limitnum = maxbuy;
              if (limitnum < 0 || (maxbuypro > 0 && limitnum > maxbuypro)) {
                limitnum = maxbuypro;
              }
              temitem["limitnum"] = limitnum
              if (limitnum >= 0) {
                if (temitem["num"] > limitnum) {
                  temitem["num"] = limitnum;
                }

              }
              if (maxbuypro > 0) {
                actlimitmodel["prolimit"][proid] -= temitem["num"]
              }
              if (maxbuy > 0) {
                actlimitmodel["maxbuy"] -= temitem["num"]
              }      

            }
          }
        }
      }
    
    
      this.setData({
        limitmodel
      })
    }
    

    return cartlist;
  },
  navtopro(e) {
   
    var data = e.currentTarget.dataset
  

    var param = "?id=" + data['id'];
    if (data['activityid']) {
      param += "&activityid=" + data['activityid']
    }
    if (data['cid']) {
      param += "&activitytype=" + data['cid']
    }
    //  id=107&activityid=12&activitytype=2
    //  console.log(param)
    wx.navigateTo({
      url: '../pro/proinfo' + param,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // console.log("aaaaaaaaaaaaa")

    // this.pause()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  
  // 编辑
  editor() {
    this.setData({
      isdelmodel: !this.data.isdelmodel
    })
  },

  /**判断是否全选 */
  vildchosedall() {
    var noselectnum = 0
    this.data.cartlist.forEach(item => {
      if (item.ischecked == false) {
        noselectnum++
      }
    })

    if (this.data.ischeckedall && noselectnum > 0) {

      this.setData({
        ischeckedall: false
      })
    } else if ((!this.data.ischeckedall) && noselectnum == 0) {

      this.setData({
        ischeckedall: true
      })
    }
  },
  // 价格计算
  price() {

    var cartlist = this.data.cartlist
    var sumclass = 0
    var sumprice = 0
    for (var a in cartlist) {
      if (cartlist[a].ischecked) {
        sumclass++;
        cartlist[a].cid=cartlist[a].cid+"";
        switch (cartlist[a].cid) {
          case "0": {
            sumprice = sumprice + cartlist[a].realprice * cartlist[a].num;
            break;
          }
          case "1": {
            sumprice = sumprice + cartlist[a].activityprice * cartlist[a].num;
            break;
          }
        }
      }
    }

    this.setData({
      sumclass: sumclass,
      sumprice: sumprice
    })
  },
  // 删除
  delete_pro() {
    var that = this;
    var cartlist = this.data.cartlist
    for (var i = cartlist.length - 1; i >= 0; i--) {
      if (cartlist[i].ischecked) {
        actcart.setnum(cartlist[i].keyval, 0)
        cartlist.splice(i, 1)

      }
    }
    this.setData({
      cartlist: cartlist
    });

    // 调用金额
    that.price();

  },

  // 全选
  choseall() {
    var ischeckedall = !this.data.ischeckedall
    var cartlist = this.data.cartlist
    for (var a in cartlist) {
      cartlist[a].ischecked = ischeckedall;
    }
    this.setData({
      cartlist: cartlist,
      ischeckedall: ischeckedall
    })

    this.price();

  },
  // 结算
  account() {
    if (this.data.sumclass > 0) {

      app.globalData.temcart = {};
      app.globalData.temcart["cid"] = 1
      app.globalData.temcart["data"] = this.data.cartlist.filter(function (item) {
        return item.ischecked;
      })
      // /integralmall/paycore/payinfo
      this.clearauto();
      wx.navigateTo({
        url: '../cart/account?iscart=1'
      })
    } else {
      wx.showToast({
        title: '请先选择商品',
        icon: 'none'
      })
    }
  },
  onClickButton() {
    if (this.data.isdelmodel) {
      var ilen = this.data.cartlist.length - 1
      var delnum = 0
      for (; ilen >= 0; ilen--) {
        if (this.data.cartlist[ilen].ischecked) {
          actcart.setnum(this.data.cartlist[ilen].keyval, 0)
          this.data.cartlist.splice(ilen, 1)
          delnum++
        }
      }

      if (delnum > 0) {
        this.setData({
          cartlist: this.data.cartlist
        })
      }
    } else {
      var cartdata = [];

      this.data.cartlist.forEach(item => {
        if (item.ischecked) {
          if(item.num>0){
            cartdata.push(item)
          }
        }
      })
      if (cartdata.length < 1) {

        wx.showToast({
          icon:"error",
          title: '请选择产品',
        })
      } else {
        console.log(app.globalData.temcart)
        app.globalData.temcart["data"] = cartdata
        wx.navigateTo({
          url: '/' + app.globalData.xcsys.m + '/integralmall/paycore/payinfo?iscart=1'
        })
      }




    }

  },
  onChangeDate(e) {
    var data = e.currentTarget.dataset
    if (!this.data.timeData[data['key']]) {
      this.data.timeData[data['key']] = {};
    }
    this.data.timeData[data['key']] = e.detail

    this.setData({
      timeData: this.data.timeData,
    });
  },
  // pause() {
  //   const countDown = this.selectComponent('.control-count-down');
  //   console.log("countDown")

  //   console.log(countDown)
  //   countDown.pause();
  // },
  blank(e) {

  },
  //清除倒计时
  clearauto: function () {
    var that = this;
    if (that.data.intervalid != -1) {
      clearInterval(that.data.intervalid)
      that.data.intervalid = -1;
    }
  },
  //倒计时 开始
  autoexcel: function (rest) {

    if (this.data.actstatus == 1) {
      var that = this;
      if (!rest) {
        if (that.data.intervalid != -1) {
          return;
        }
      } else {
        this.clearauto();
      }
      that.data.intervalid = setInterval(function () {

        that.setData({
          aunttime: new Date()
        })
      }, 1000)
    }


  },
})